package com.qst.controller;

import com.qst.beans.User;
import com.qst.service.impl.UserServiceImpl;
import com.qst.util.CreateYanZhen;
import com.qst.util.EmailUtils;
import com.qst.util.MD5Encoding;
import com.qst.util.RandomNum;
import com.sun.deploy.net.HttpResponse;
import org.apache.ibatis.annotations.Param;
//import org.apache.struts2.ServletActionContext;
//import org.apache.tools.ant.types.resources.selectors.None;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Controller
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    @RequestMapping(value = "/user_findByName")
    @ResponseBody
    public String findByName(@Param("username") String username, HttpServletRequest request){
//        username = request.getParameter("username");
        System.out.println("名称验证:" + username);
        User existUser = userService.findByName(username);
        System.out.println("existUser:" + existUser);
//        response.setContentType("text/html;charset=utf-8");
//        PrintWriter out = response.getWriter();
        if (existUser != null ) {
            return "exist";
        } else {
            return "ok";
        }
    }

    @RequestMapping(value = "/user_login", method = RequestMethod.POST)
    public String userLogin(User user, HttpSession session,HttpServletRequest request) {
        String randomcodekey = (String)session.getAttribute("RANDOMVALIDATECODEKEY");
        System.out.println("登录者：" + user);
        System.out.println("登录验证码:"+randomcodekey);
        if(!randomcodekey.equals(user.getCode())){
            request.setAttribute("msg","验证码错误");
            return "views/login";
        }
        User enterUser = userService.findByName(user.getUsername());
        if (enterUser != null) {
            System.out.println(enterUser.toString());
            if (MD5Encoding.getMD5(user.getPassword()).equals(enterUser.getPassword())) {
                session.setAttribute("enterUser", enterUser);//将登陆者信息保存到session作用域中
                return "redirect: /user_indexPage";
            }else
                request.setAttribute("msg","密码错误");
        }else
            request.setAttribute("msg","账号错误");
        return "views/login";
    }


    @RequestMapping("/user_regist")
    public String userRegist(User user,HttpServletRequest request,HttpSession session) {
        System.out.println("注册者:" + user);
        int i = 0;
        if (user != null) {
            String pwd = MD5Encoding.getMD5(user.getPassword());
            user.setPassword(pwd);
            i = userService.addUser(user);
        }
        String registCode = "";
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("registCode")){
                registCode = cookie.getValue();
            }
        }
        System.out.println("发送的注册码:"+registCode);
        if(registCode==null || !registCode.equals(user.getCode())){
            request.setAttribute("msg","验证码错误");
            return "views/regist";
        }
        System.out.println("注册是否成功?" + i);
        if (i > 0) {
            return "views/login";
        } else {
            request.setAttribute("msg","用户名已存在");
            return "views/regist";
        }
    }

    /**
     * 发送注册验证码到邮箱
     * @param email
     * @param request
     * @param response
     */
    @RequestMapping("/send_code_email")
    @ResponseBody
    public String  sendCodeEmail(String email, HttpServletRequest request, HttpServletResponse response){
        String registCode = RandomNum.createNumRandom(4);
        EmailUtils.sendEmail(email,"农产品推荐平台注册验证码",registCode);
        Cookie cookie = new Cookie("registCode", registCode);
        cookie.setMaxAge(3*60);
        response.addCookie(cookie);
        if(registCode!=null){
            return "1";
        }
        return "0";
    }


    @RequestMapping("/user_logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect: /user_indexPage";
    }

    /*验证码生成*/
    @RequestMapping("/checkImg")
    public void setCodeImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        CreateYanZhen randomValidateCode = new CreateYanZhen();
        try {
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
